#include "loginwidget.h"
#include "ui_loginwidget.h"
#include <QMessageBox>
#include <QCryptographicHash>

LogInWidget::LogInWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LogInWidget)
{
    ui->setupUi(this);

}

LogInWidget::~LogInWidget()
{
    delete ui;
}

void LogInWidget::on_submitButton_clicked()
{
    UserData *user = new UserData(NULL);
    user->setUserName(ui->usernameEdit->text());
    qDebug() << qPrintable(user->getUserName());
    /*
    //Exmaple:
    QString password = "jaekwang ";

    QCryptographicHash hash(QCryptographicHash::Sha1);
    hash.addData(password.toUtf8());
    QString hashed = hash.result().toHex();

    qDebug() << hashed;
     */
    QString password = ui->passwordEdit->text();
    QCryptographicHash hash(QCryptographicHash::Sha1);
    hash.addData(password.toUtf8());
    QString hashed_pw = hash.result().toHex();

    user->setHashedPassword(hashed_pw);
    qDebug() << qPrintable(user->getHashedPassword());

    qDebug() << "Emitting signal login";
    emit login(user);
}

void LogInWidget::handleSuccessfulLogin(UserData *userData)
{
    emit launchUI(userData);
    this->close();
}

void LogInWidget::handleLoginError(QString errorMessage)
{
    QMessageBox::information(this, tr("Login Failed"), errorMessage);
}

void LogInWidget::on_settingButton_clicked()
{
    setting = new SettingDialog;
    connect(setting, SIGNAL(changeIpPortNumber(QString,int)), this, SLOT(sendIPPort(QString, int)));

    setting->setAttribute(Qt::WA_DeleteOnClose);
    setting->setModal(true);
    setting->exec();
}

void LogInWidget::sendIPPort(QString ip, int port)
{
    emit sendIPPortToMainWidget(ip, port);
}
